import sys 
sys.path.append("core_q2_id")
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from plotly.offline import download_plotlyjs, init_notebook_mode,  plot
from Surface_Plot  import surface_parameters, surface_parameters_orig
import plotly.graph_objects as go 
import numpy as np

Nt_new = 85
Nr_new = 146
#X=np.loadtxt('Estimated_parameters.txt') 

X = np.loadtxt("./core_q2_id/data_q2_id.txt")
#Scale the points
scaler = MinMaxScaler()
#scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
inertia = []

#Determine the optimal number of clusters
for i in range(1,11):
    kmeans = KMeans(n_clusters=i, init="k-means++",n_init=10,tol=1e-04)
    kmeans.fit(X)
    inertia.append(kmeans.inertia_)
# fig = go.Figure(data=go.Scatter(x=np.arange(1,11),y=inertia))

# fig.update_layout(title="Inertia vs Cluster Number",xaxis=dict(range=[0,11],title="Cluster Number"),
#                   yaxis={'title':'Inertia'}, annotations=[
#         dict(
#             x=4,
#             y=inertia[3],
#             xref="x",
#             yref="y",
#             text="Elbow! (Optimal number of cluseters)",
#             showarrow=True,
#             arrowhead=7,
#             ax=20,
#             ay=-40
#         )])

# fig.write_image('Elbow.pdf')
# plot(fig)

#Perform the clustering
kmeans = KMeans(
        n_clusters=4, init="k-means++",
        n_init=10,
        tol=1e-04, random_state=10)

kmeans.fit(X)
#Obtain the centers of the clusters
parameters_LSTM_scaled = kmeans.cluster_centers_
parameters_LSTM_unscaled = parameters_LSTM_scaled*(scaler.data_max_ - scaler.data_min_) + scaler.data_min_

#Obtain the clusters
X_clustered = np.zeros((X.shape[0], 7))
X_clustered[:,0:6] = X
X_clustered[:,6] = kmeans.labels_

#Plot the clusters
shape_1 = Nt_new
shape_2 = Nr_new

clusters_reshaped = np.reshape(kmeans.labels_, (shape_1, shape_2))

Tr=surface_parameters_orig(clusters_reshaped,'tr',' ',' ')


# np.savetxt('Clustered_points_new.txt', X_clustered)
# np.savetxt('Parameters_LSTM_new.txt', parameters_LSTM_unscaled)

